package com.poisonh.unifiedauth.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.lzy.okhttputils.model.HttpParams;
import com.poisonh.unifiedauth.R;
import com.poisonh.unifiedauth.dao.UserinfoDaoImpl;
import com.poisonh.unifiedauth.dialog.EducationDialogFragment;
import com.poisonh.unifiedauth.model.UserInfoModel;
import com.poisonh.unifiedauth.ui.svprogresshud.SVProgressHUD;
import com.poisonh.unifiedauth.utils.ConstantUitls;
import com.poisonh.unifiedauth.utils.MyHttpsUtils;
import com.poisonh.unifiedauth.utils.ToastUtils;
import com.zhy.autolayout.AutoRelativeLayout;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 学历证书
 * Created by PoisonH on 2016/7/7.
 */
public class SettingScoreActivity extends BaseActivity implements View.OnClickListener, EducationDialogFragment.ChooseEduListener
{
    //省份布局
    private AutoRelativeLayout arlSettingScoreA;
    //学校布局
    private AutoRelativeLayout arlSettingScoreB;
    //学历布局
    private AutoRelativeLayout arlSettingScoreC;
    //身份
    private TextView mTvProvince;
    //学校
    private TextView mTvSchool;
    //学历
    private TextView mTvEducation;
    //学历编号
    private EditText mEducationNumber;
    //提交按钮
    private Button mBtnCommit;

    private String mStrProvince;
    private String mStrProvinceNumber;
    private String mStrSchool;
    private String mStrSchoolNumber;
    private String mStrEducation;
    private String mStrEducationNumber;

    @Override
    protected void loadContentView(Bundle savedInstanceState)
    {
        if (savedInstanceState != null)
        {
            mStrProvince = savedInstanceState.getString("Province");
            mStrSchool = savedInstanceState.getString("School");
        }
        setContentView(R.layout.activity_settingscore);
        initTitleView();
        initView();
        getEducation();
    }

    @Override
    protected void initView()
    {
        mRightBtn.setVisibility(View.GONE);
        mLeftBtn.setOnClickListener(this);
        setTitleTxt("学历证书");

        arlSettingScoreA = (AutoRelativeLayout) findViewById(R.id.arl_setting_score_a);
        arlSettingScoreB = (AutoRelativeLayout) findViewById(R.id.arl_setting_score_b);
        arlSettingScoreC = (AutoRelativeLayout) findViewById(R.id.arl_setting_score_c);
        mTvProvince = (TextView) findViewById(R.id.tv_settingscore_province);
        mTvSchool = (TextView) findViewById(R.id.tv_settingscore_school);
        mTvEducation = (TextView) findViewById(R.id.tv_settingscore_education);
        mEducationNumber = (EditText) findViewById(R.id.input_education_number);
        mEducationNumber.addTextChangedListener(mBtnTextWatcher);
        mBtnCommit = (Button) findViewById(R.id.btn_commit);
        arlSettingScoreA.setOnClickListener(this);
        arlSettingScoreB.setOnClickListener(this);
        arlSettingScoreC.setOnClickListener(this);
        mBtnCommit.setOnClickListener(this);
    }

    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.arl_setting_score_a:
                startActivityForResult(new Intent(SettingScoreActivity.this, ProvinceActivity.class), 100);
                break;
            case R.id.arl_setting_score_b:
                if (mStrProvince.isEmpty())
                {
                    ToastUtils.showToast(this, "请先选择省份");
                } else
                {
                    Intent mIntent = new Intent(SettingScoreActivity.this, SchoolActivity.class);
                    mIntent.putExtra("PROID", mStrProvinceNumber);
                    startActivityForResult(mIntent, 101);
                }
                break;
            case R.id.arl_setting_score_c:
                EducationDialogFragment dialogFragment = new EducationDialogFragment();
                dialogFragment.show(getFragmentManager(), "");
                break;
            case R.id.btn_commit:
                mStrEducationNumber = mEducationNumber.getText().toString();
                if (mStrEducationNumber.length() < 17)
                {
                    ToastUtils.showToast(this, "请输入17或者18位学历编号");
                } else
                {
                    if (mStrProvince == null || mStrProvinceNumber == null ||//
                            mStrSchool == null || mStrSchoolNumber == null || //
                            mStrEducation == null || mStrEducationNumber == null)//
                    {
                        ToastUtils.showToast(this, "请完善信息");
                    } else
                    {
                        commit();
                    }
                }
                break;
            case R.id.ib_left_btn:
                finish();
                break;
        }
    }

    /**
     * 提交用户信息
     */
    private void commit()
    {
        SVProgressHUD.showWithStatus(this, "加载中...");

        HttpParams params = new HttpParams();
        params.put("id", mStrUserId);
        params.put("token", mStrUserToken);
        //学校编号
        params.put("sch_id", mStrSchoolNumber);
        //学历编号
        params.put("edu_num", mStrEducationNumber);
        //学历文凭
        params.put("education", mStrEducation);
        //省份编号
        params.put("pro_id", mStrProvinceNumber);

        MyHttpsUtils.post(ConstantUitls.REQUEDT_URL + ConstantUitls.ADDEDUINFO, params, new MyHttpsUtils.ResultCallback()
        {
            @Override
            public void onSuccess(String response)
            {
                ToastUtils.showToast(SettingScoreActivity.this, "信息更新成功");
                finish();
                try
                {
                    //根据id查询用户
                    UserinfoDaoImpl mUserinfoDaoImpl = new UserinfoDaoImpl(SettingScoreActivity.this);
                    UserInfoModel model = mUserinfoDaoImpl.queryReturnOne(mStrUserId);
                    model.setmStrEducation("审核中");
                    mUserinfoDaoImpl.commit();
                } catch (Exception e)
                {
                    e.printStackTrace();
                }
                SVProgressHUD.dismiss(SettingScoreActivity.this);
            }

            @Override
            public void onFailure(String failReason)
            {
                ToastUtils.showToast(SettingScoreActivity.this, "信息更新失败");
                SVProgressHUD.dismiss(SettingScoreActivity.this);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode)
        {
            case 100:
                if (!data.getStringExtra("PROID").equals("-1"))
                {
                    mStrProvinceNumber = data.getStringExtra("PROID");
                    mStrProvince = data.getStringExtra("PRONAME");
                    mTvProvince.setText(mStrProvince);
                }
                break;
            case 101:
                if (!data.getStringExtra("SCHID").equals("-1"))
                {
                    mStrSchoolNumber = data.getStringExtra("SCHID");
                    mStrSchool = data.getStringExtra("SCHNAME");
                    mTvSchool.setText(mStrSchool);
                }
                break;
        }

    }

    @Override
    public void onChooseEduListener(String edu)
    {
        mStrEducation = edu;
        mTvEducation.setText(mStrEducation);
    }

    /**
     * 获取学历
     */
    private void getEducation()
    {
        SVProgressHUD.showWithStatus(this, "加载中...");
        HttpParams params = new HttpParams();
        params.put("id", mStrUserId);
        params.put("token", mStrUserToken);
        MyHttpsUtils.post(ConstantUitls.REQUEDT_URL + ConstantUitls.GETEDUCATION, params, new MyHttpsUtils.ResultCallback()
        {
            @Override
            public void onSuccess(String response)
            {
                Message msg = Message.obtain();
                msg.obj = response;
                mHandler.sendMessage(msg);
                SVProgressHUD.dismiss(SettingScoreActivity.this);
            }

            @Override
            public void onFailure(String failReason)
            {
                SVProgressHUD.dismiss(SettingScoreActivity.this);
            }
        });
    }

    Handler mHandler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);
            try
            {
                JSONObject object = new JSONObject((String) msg.obj);
                JSONObject data = object.getJSONObject("results");
                mStrProvince = data.getString("pro_name");
                mStrSchool = data.getString("sch_name");
                mStrSchoolNumber = data.getString("sch_id");
                mStrProvinceNumber = data.getString("pro_id");
                mStrEducationNumber = data.getString("edu_num");
                mStrEducation = data.getString("education");
                if (mStrProvince != null)
                {
                    mTvProvince.setText(mStrProvince);
                }
                if (mStrSchool != null)
                {
                    mTvSchool.setText(mStrSchool);
                }
                mTvEducation.setText(mStrEducation);
                if (mStrEducationNumber != null)
                {
                    mEducationNumber.setText(mStrEducationNumber);
                    //将光标移到文字后面
                    Editable etext = mEducationNumber.getText();
                    Selection.setSelection(etext, etext.length());
                }

            } catch (JSONException e)
            {
                e.printStackTrace();
            }
        }
    };

    @Override
    protected void onPause()
    {
        super.onPause();
    }

    /**
     * 保存省份、学校信息
     *
     * @param outState
     */
    @Override
    public void onSaveInstanceState(Bundle outState)
    {
        super.onSaveInstanceState(outState);
        if (mStrProvince != null)
        {
            outState.putString("Province", mStrProvince);
        }
        if (mStrSchool != null)
        {
            outState.putString("School", mStrSchool);
        }
    }

    TextWatcher mBtnTextWatcher = new TextWatcher()
    {
        private CharSequence temp;

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after)
        {
            temp = s;
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count)
        {

        }

        @Override
        public void afterTextChanged(Editable s)
        {
            if (temp.length() >= 17)
            {
                mBtnCommit.setEnabled(true);
                mBtnCommit.setBackground(getResources().getDrawable(R.drawable.shape_settingmyinfo_btn_bg));
            } else
            {
                mBtnCommit.setEnabled(false);
                mBtnCommit.setBackground(getResources().getDrawable(R.drawable.shape_settingmyinfo_btn_bg_));
            }
        }
    };

}
